package sm.clientHandler;

import java.net.*;
import java.io.*;

import sm.routine.WorkloadMonitor;
import sm.utils.PropertySet;

public class ClientHandler {



	public static void main(String args[]) throws Exception {
		//create socket listen to request
		ServerSocket listenSocket = new ServerSocket(PropertySet._DocMngSocket);
		System.out.println("server Start...");

		//looping to wait for requests
		while(true){
			//Listen to socket & accept request from clients
			Socket connectionSocket = listenSocket.accept();
			System.out.println("Accepting Connection...");
			//if (connectionSocket != null){
			
			ServConnect connection = new ServConnect();
			connection.start();
				//Client client = new Client(connectionSocket);
				
				//client.start();
			}

			
		}
	}

	class Client extends Thread{

		private Socket connectionSocket;
		private String clientSentence;
		private String ans;
		private BufferedReader inFromClient;
		private DataOutputStream outToClient;
		private DataOutputStream outToDWS;
		private BufferedReader inFromDWS;


		public Client(Socket c) throws IOException
		{
			connectionSocket = c;
		}

		public void run() 
		{
			try
			{ 
				System.out.println("Hello");
				inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
				outToClient = new DataOutputStream(connectionSocket.getOutputStream());
				//clientSentence = inFromClient.readLine();
				System.out.println("Data received: " + clientSentence);
				try
				{
					System.out.println("Connecting to DWS");
					Socket socket = new Socket("10.12.0.134", 10001);
					outToDWS = new DataOutputStream(socket.getOutputStream());
					inFromDWS = new BufferedReader(new InputStreamReader(socket.getInputStream()));
					System.out.println("Connection successful");
					outToDWS.writeBytes("http://simone4.edublogs.org/files/2011/02/kittykat-19qh78w.jpg\neom");
					outToDWS.flush();
					//outToDWS.close();
					//clientSentence = inFromDWS.readLine();
					while((clientSentence = inFromDWS.readLine())!="eom"){
						//clientSentence = inFromDWS.readLine();
						if (clientSentence == null)
							break;
						System.out.println("http://10.12.0.134:10000/"+clientSentence);
						//System.out.println(clientSentence);
					}
					socket.close();
					
					//System.out.println("http://10.12.0.134:10000/"+clientSentence);
					
					//BufferedWriter writer = new BufferedWriter( new FileWriter( "database.txt" , true ) );
					//writer.write(clientSentence + "\n");
					//writer.close(); 
				}
				catch (IOException e)
				{
					System.out.println("Exception  "+ e);
				}

			}
			catch(IOException e)
			{
				System.out.println("Error: " + e);
			}
		}
	}


